package com.zero.service;

import com.zero.entity.FamilyMember;
import com.zero.entity.Menu;
import com.zero.mapper.FamilyMemberMapper;
import com.zero.mapper.MenuMapper;
import com.zero.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 根据菜单类型查询用户菜单
     * @param type 用户类型
     * @return
     */
    private Result getMenus(int type){

        Menu param = new Menu();
        param.setType(type);

        //查出所有type==0的菜单
        List<Menu> menus = menuMapper.select(param);

        //存放一级菜单
        List<Menu> topMenus = new ArrayList<>();
        for (Menu menu : menus) {
            //找出一级菜单
            if (menu.getParentId() == 0) {
                //找出一级的子菜单并添加到一级菜单的子菜单集合中
                List<Menu> child = new ArrayList<>();
                for (Menu temp : menus) {
                    if (temp.getParentId() == menu.getId())
                        child.add(temp);
                }
                menu.setChild(child);
                //将一级菜单放置到菜单集合中
                topMenus.add(menu);
            }
        }
//        log.info("输出菜单信息：");
//        log.info(topMenus.toString());
        return Result.ok(topMenus);
    }

    public Result getAdminMenu(){
        return getMenus(0);
    }

    public Result getFamilyMemberMenu(int familyMemberId){
        FamilyMember familyMember = familyMemberMapper.selectById(familyMemberId);
        return getMenus(familyMember.getType()+1);
    }



}
